package com.qys.livesMall.navy.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Sets;
import com.qys.livesMall.anchor.business.LiveRoomBusiness;
import com.qys.livesMall.anchor.constants.RedisConstant;
import com.qys.livesMall.anchor.model.dto.lives.app.LikeLivesRoomDTO;
import com.qys.livesMall.app.user.constants.TencentCloudImConstant;
import com.qys.livesMall.app.user.mapper.H2AppUserMapper;
import com.qys.livesMall.app.user.model.entity.H2AppUser;
import com.qys.livesMall.app.user.utils.TencentCloudIm;
import com.qys.livesMall.cache.RedisCache;
import com.qys.livesMall.common.exception.enums.ExceptionEnum;
import com.qys.livesMall.common.message.MessageServer;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.navy.common.Constant;
import com.qys.livesMall.navy.dao.NavyTaskDetailDao;
import com.qys.livesMall.navy.model.dto.task.AddAnchorCollect;
import com.qys.livesMall.navy.model.entity.NavyTask;
import com.qys.livesMall.navy.model.entity.NavyTaskDetail;
import com.qys.livesMall.navy.service.NavyLivesGiveLikeService;
import com.qys.livesMall.navy.service.NavyTaskDetailService;
import com.qys.livesMall.navy.service.NavyTaskService;
import com.qys.livesMall.navy.task.TaskInter;
import com.qys.livesMall.shop.open.anchor.service.AnchorServer;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class NavyLivesGiveLikeServiceImpl implements NavyLivesGiveLikeService {

    @Resource
    private MessageServer messageServer;
    @Resource
    private NavyTaskService navyTaskService;
    @Resource
    private NavyTaskDetailService navyTaskDetailService;
    @Resource
    private LiveRoomBusiness liveRoomBusiness;
    @Resource
    private NavyTaskDetailDao navyTaskDetailDao;
    @Resource
    private TencentCloudIm tencentCloudIm;
    @Resource
    private RedisCache redisCache;
    @Resource
    private AnchorServer anchorServer;
    @Resource
    private H2AppUserMapper appUserMapper;
    @Resource
    @Lazy
    private TaskInter taskInter;

    @Override
    public R<?> livesGiveLike(AddAnchorCollect param) {
        if (param == null || CollectionUtils.isEmpty(param.getNavyIds()) || CollectionUtils.isEmpty(param.getLivesIds())) {
            return messageServer.failMsg(ExceptionEnum.PARAM_IS_ERROR);
        }
        NavyTask navyTask = new NavyTask();
        navyTask.setTaskType(Constant.TaskType.ANCHOR_COLLECT);
        navyTask.setTaskName("主播点赞");
        navyTask.setTaskParam(JSONObject.toJSONString(param));
        navyTask.setTaskStatus(Constant.TaskStatus.RUNNING);
        navyTask.setTaskStartTime(LocalDateTime.now());
        navyTask.setCreateDate(LocalDateTime.now());
        navyTask.setUpdDate(LocalDateTime.now());
        navyTaskService.save(navyTask);
        //创建任务明细
        NavyTaskDetail detail = new NavyTaskDetail();
        detail.setTaskId(navyTask.getId());
        detail.setTaskType(navyTask.getTaskType());
        detail.setSort(1);
        detail.setNavyIds(String.join(",", param.getNavyIds()));
        detail.setLivesIds(JSONObject.toJSONString(param.getLivesIds()));
        detail.setCreateDate(LocalDateTime.now());
        detail.setTaskStatus(Constant.TaskDetailStatus.NO_START);
        navyTaskDetailDao.save(detail);
        taskInter.addLivesGiveLikeTask(1, detail.getId());
        return R.ok();
    }

    @Override
    @Async
    public void exc(Long taskDetailId) {
        NavyTaskDetail detail = navyTaskDetailService.getById(taskDetailId);
        if (detail == null) {
            return;
        }
        List<String> livesIds = JSONArray.parseArray(detail.getLivesIds()).toList(String.class);
        try {
            livesIds.forEach(livesId -> {
                //获取直播间编号
                String roomNumber = anchorServer.getRoomInfoByLivesSessionId(Long.valueOf(livesId));
                if (StringUtils.isNotEmpty(roomNumber)) {
                    String[] navyIdList = detail.getNavyIds().split(",");
                    for (String navyId : navyIdList) {
                        //计入观看人数
                        String key = RedisConstant.LIVE_ONLINE_NUMBER_PREFIX + livesId;
                        Long size = redisCache.size(key);
                        Set<String> cacheSet;
                        if(size == 0){
                            cacheSet = Sets.newHashSet("navy" + navyId);
                            //伪装进入直播间
                            tencentCloudIm.sendGroupMsg(navyId, anchorServer.getRoomInfoByLivesSessionId(Long.valueOf(livesId)), TencentCloudImConstant.TIM_CUSTOM_ELEM, "enter");
                        } else {
                            cacheSet = redisCache.getCacheSet(key);
                            if(!redisCache.getCacheSet(key).contains("navy" + navyId)){
                                //伪装进入直播间
                                tencentCloudIm.sendGroupMsg(navyId, anchorServer.getRoomInfoByLivesSessionId(Long.valueOf(livesId)), TencentCloudImConstant.TIM_CUSTOM_ELEM, "enter");
                                cacheSet.add("navy" + navyId);
                            }
                        }
                        redisCache.setCacheSet(key, cacheSet);

                        try {
                            Thread.sleep(RandomUtil.randomLong(5000, 10000));
                        } catch (Exception ignored) {

                        }

                        int likeNum = RandomUtil.randomInt(1, 20);
                        H2AppUser appUser = appUserMapper.selectById(navyId);
                        tencentCloudIm.sendGroupMsg(navyId, anchorServer.getRoomInfoByLivesSessionId(Long.valueOf(livesId)), TencentCloudImConstant.TIM_CUSTOM_ELEM, likeNum + "," + appUser.getNickName());

                        LikeLivesRoomDTO likeLivesRoomDTO = new LikeLivesRoomDTO();
                        likeLivesRoomDTO.setLivesRoomNum(roomNumber);
                        likeLivesRoomDTO.setLivesSessionId(Long.valueOf(livesId));
                        likeLivesRoomDTO.setLikeNum(likeNum);
                        liveRoomBusiness.giveLikeLivesRoom(likeLivesRoomDTO);
                    }
                }
            });
        } catch (Exception e) {
            detail.setTaskStatus(Constant.TaskDetailStatus.END_FAIL);
            detail.setTaskDate(LocalDateTime.now());
            navyTaskDetailService.upById(detail);
            return;
        }

        detail.setTaskStatus(Constant.TaskDetailStatus.END_SUCCESS);
        navyTaskDetailService.upById(detail);
        //同步主任务状态
        navyTaskService.watchTaskEnd(detail.getTaskId());
    }
}
